<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- /fasttmp/mkdist-qt-4.3.5-1211793125/qtopia-core-opensource-src-4.3.5/doc/src/examples/fortuneclient.qdoc -->
<head>
  <title>Qt 4.3: Fortune Client Example</title>
  <link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http://www.trolltech.com/products/qt"><img src="images/qt-logo.png" align="left" width="32" height="32" border="0" /></a></td>
<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="mainclasses.html"><font color="#004faf">Main&nbsp;Classes</font></a>&nbsp;&middot; <a href="groups.html"><font color="#004faf">Grouped&nbsp;Classes</font></a>&nbsp;&middot; <a href="modules.html"><font color="#004faf">Modules</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">Functions</font></a></td>
<td align="right" valign="top" width="230"><a href="http://www.trolltech.com"><img src="images/trolltech-logo.png" align="right" width="203" height="32" border="0" /></a></td></tr></table><h1 align="center">Fortune Client Example<br /><small></small></h1>
<p>Files:</p>
<ul>
<li><a href="network-fortuneclient-client-cpp.html">network/fortuneclient/client.cpp</a></li>
<li><a href="network-fortuneclient-client-h.html">network/fortuneclient/client.h</a></li>
<li><a href="network-fortuneclient-main-cpp.html">network/fortuneclient/main.cpp</a></li>
</ul>
<p>The Fortune Client example shows how to create a client for a simple network service using <a href="qtcpsocket.html">QTcpSocket</a>. It is intended to be run alongside the <a href="network-fortuneserver.html">Fortune Server</a> example or the <a href="network-threadedfortuneserver.html">Threaded Fortune Server</a> example.</p>
<p align="center"><img src="images/fortuneclient-example.png" alt="Screenshot of the Fortune Client example" /></p><p>This example uses a simple <a href="qdatastream.html">QDataStream</a>-based data transfer protocol to request a line of text from a fortune server (from the <a href="network-fortuneserver.html">Fortune Server</a> example). The client requests a fortune by simply connecting to the server. The server then responds with a 16-bit (<a href="qtglobal.html#quint16-typedef">quint16</a>) integer containing the length of the fortune text, followed by a <a href="qstring.html">QString</a>.</p>
<p><a href="qtcpsocket.html">QTcpSocket</a> supports two general approaches to network programming:</p>
<ul>
<li><i>The asynchronous (non-blocking) approach.</i> Operations are scheduled and performed when control returns to Qt's event loop. When the operation is finished, <a href="qtcpsocket.html">QTcpSocket</a> emits a signal. For example, <a href="qabstractsocket.html#connectToHost">QTcpSocket::connectToHost</a>() returns immediately, and when the connection has been established, <a href="qtcpsocket.html">QTcpSocket</a> emits <a href="qabstractsocket.html#connected">connected()</a>.</li>
<li><i>The synchronous (blocking) approach.</i> In non-GUI and multithreaded applications, you can call the <tt>waitFor...()</tt> functions (e.g&#x2e;, <a href="qabstractsocket.html#waitForConnected">QTcpSocket::waitForConnected</a>()) to suspend the calling thread until the operation has completed, instead of connecting to signals.</li>
</ul>
<p>In this example, we will demonstrate the asynchronous approach. The <a href="network-blockingfortuneclient.html">Blocking Fortune Client</a> example illustrates the synchronous approach.</p>
<p>Our class contains some data and a few private slots:</p>
<pre> class Client : public QDialog
 {
     Q_OBJECT

 public:
     Client(QWidget *parent = 0);

 private slots:
     void requestNewFortune();
     void readFortune();
     void displayError(QAbstractSocket::SocketError socketError);
     void enableGetFortuneButton();

 private:
     QLabel *hostLabel;
     QLabel *portLabel;
     QLineEdit *hostLineEdit;
     QLineEdit *portLineEdit;
     QLabel *statusLabel;
     QPushButton *getFortuneButton;
     QPushButton *quitButton;
     QDialogButtonBox *buttonBox;

     QTcpSocket *tcpSocket;
     QString currentFortune;
     quint16 blockSize;
 };</pre>
<p>Other than the widgets that make up the GUI, the data members include a <a href="qtcpsocket.html">QTcpSocket</a> pointer, a copy of the fortune text currently displayed, and the size of the packet we are currently reading (more on this later).</p>
<p>The socket is initialized in the Client constructor. We'll pass the main widget as parent, so that we won't have to worry about deleting the socket:</p>
<pre> Client::Client(QWidget *parent)
     : QDialog(parent)
 {
     ...
     tcpSocket = new QTcpSocket(this);</pre>
<p>The only <a href="qtcpsocket.html">QTcpSocket</a> signals we need in this example are <a href="qiodevice.html#readyRead">QTcpSocket::readyRead</a>(), signifying that data has been received, and <a href="qabstractsocket.html#error">QTcpSocket::error</a>(), which we will use to catch any connection errors:</p>
<pre>     ...
     connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readFortune()));
     connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
     ...
 }</pre>
<p>Clicking the <b>Get Fortune</b> button will invoke the <tt>requestNewFortune()</tt> slot:</p>
<pre> void Client::requestNewFortune()
 {
     getFortuneButton-&gt;setEnabled(false);
     blockSize = 0;
     tcpSocket-&gt;abort();
     tcpSocket-&gt;connectToHost(hostLineEdit-&gt;text(),
                              portLineEdit-&gt;text().toInt());
 }</pre>
<p>In this slot, we initialize <tt>blockSize</tt> to 0, preparing to read a new block of data. Because we allow the user to click <b>Get Fortune</b> before the previous connection finished closing, we start off by aborting the previous connection by calling <a href="qabstractsocket.html#abort">QTcpSocket::abort</a>(). (On an unconnected socket, this function does nothing.) We then proceed to connecting to the fortune server by calling <a href="qabstractsocket.html#connectToHost">QTcpSocket::connectToHost</a>(), passing the hostname and port from the user interface as arguments.</p>
<p>As a result of calling <a href="qabstractsocket.html#connectToHost">connectToHost()</a>, one of two things can happen:</p>
<ul>
<li><i>The connection is established.</i> In this case, the server will send us a fortune. <a href="qtcpsocket.html">QTcpSocket</a> will emit <a href="qiodevice.html#readyRead">readyRead()</a> every time it receives a block of data.</li>
<li><i>An error occurs.</i> We need to inform the user if the connection failed or was broken. In this case, <a href="qtcpsocket.html">QTcpSocket</a> will emit <a href="qabstractsocket.html#error">error()</a>, and <tt>Client::displayError()</tt> will be called.</li>
</ul>
<p>Let's go through the <a href="qabstractsocket.html#error">error()</a> case first:</p>
<pre> void Client::displayError(QAbstractSocket::SocketError socketError)
 {
     switch (socketError) {
     case QAbstractSocket::RemoteHostClosedError:
         break;
     case QAbstractSocket::HostNotFoundError:
         QMessageBox::information(this, tr(&quot;Fortune Client&quot;),
                                  tr(&quot;The host was not found. Please check the &quot;
                                     &quot;host name and port settings.&quot;));
         break;
     case QAbstractSocket::ConnectionRefusedError:
         QMessageBox::information(this, tr(&quot;Fortune Client&quot;),
                                  tr(&quot;The connection was refused by the peer. &quot;
                                     &quot;Make sure the fortune server is running, &quot;
                                     &quot;and check that the host name and port &quot;
                                     &quot;settings are correct.&quot;));
         break;
     default:
         QMessageBox::information(this, tr(&quot;Fortune Client&quot;),
                                  tr(&quot;The following error occurred: %1.&quot;)
                                  .arg(tcpSocket-&gt;errorString()));
     }

     getFortuneButton-&gt;setEnabled(true);
 }</pre>
<p>We pop up all errors in a dialog using <a href="qmessagebox.html#information">QMessageBox::information</a>(). <a href="qabstractsocket.html#SocketError-enum">QTcpSocket::RemoteHostClosedError</a> is silently ignored, because the fortune server protocol ends with the server closing the connection.</p>
<p>Now for the <a href="qiodevice.html#readyRead">readyRead()</a> alternative. This signal is connected to <tt>Client::readFortune()</tt>:</p>
<pre> void Client::readFortune()
 {
     QDataStream in(tcpSocket);
     in.setVersion(QDataStream::Qt_4_0);

     if (blockSize == 0) {
         if (tcpSocket-&gt;bytesAvailable() &lt; (int)sizeof(quint16))
             return;

         in &gt;&gt; blockSize;
     }

     if (tcpSocket-&gt;bytesAvailable() &lt; blockSize)
         return;</pre>
<p>The protocol is based on <a href="qdatastream.html">QDataStream</a>, so we start by creating a stream object, passing the socket to <a href="qdatastream.html">QDataStream</a>'s constructor. We then explicitly set the protocol version of the stream to <a href="qdatastream.html#Version-enum">QDataStream::Qt_4_0</a> to ensure that we're using the same version as the fortune server, no matter which version of Qt the client and server use.</p>
<p>Now, TCP is based on sending a stream of data, so we cannot expect to get the entire fortune in one go. Especially on a slow network, the data can be received in several small fragments. <a href="qtcpsocket.html">QTcpSocket</a> buffers up all incoming data and emits <a href="qiodevice.html#readyRead">readyRead()</a> for every new block that arrives, and it is our job to ensure that we have received all the data we need before we start parsing. The server's response starts with the size of the packet, so first we need to ensure that we can read the size, then we will wait until <a href="qtcpsocket.html">QTcpSocket</a> has received the full packet.</p>
<pre>     QString nextFortune;
     in &gt;&gt; nextFortune;

     if (nextFortune == currentFortune) {
         QTimer::singleShot(0, this, SLOT(requestNewFortune()));
         return;
     }

     currentFortune = nextFortune;
     statusLabel-&gt;setText(currentFortune);
     getFortuneButton-&gt;setEnabled(true);
 }</pre>
<p>We proceed by using <a href="qdatastream.html">QDataStream</a>'s streaming operator to read the fortune from the socket into a <a href="qstring.html">QString</a>. Once read, we can call <a href="qlabel.html#text-prop">QLabel::setText</a>() to display the fortune.</p>
<p>See also <a href="network-fortuneserver.html">Fortune Server Example</a> and <a href="network-blockingfortuneclient.html">Blocking Fortune Client Example</a>.</p>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="30%">Copyright &copy; 2008 <a href="trolltech.html">Trolltech</a></td>
<td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="30%" align="right"><div align="right">Qt 4.3.5</div></td>
</tr></table></div></address></body>
</html>
